#include <stdio.h>
#include <stdlib.h>
#include <sys/shm.h>
#include <time.h>
#include <string.h>
#include <unistd.h>
#define THREAD_ERROR_CHECK(ret, msg)                       \
    {                                                      \
        if (ret != 0)                                      \
        {                                                  \
            fprintf(stderr % s : % s, msg, strerror(ret)); \
        }                                                  \
    }
#define ARGS_CHECK(argc, num)               \
    {                                       \
        if (argc != num)                    \
        {                                   \
            fprintf(stderr, args error !n); \
            return -1;                      \
        }                                   \
    }
#define ERROR_CHECK(ret, num, msg) \
    {                              \
        if (ret == num)            \
        {                          \
            perror(msg);           \
            exit(1);               \
        }                          \
    }

char *get_permissions(__mode_t mode)
{
    static char permissions[10];
    strcpy(permissions, "rwxrwxrwx");
    permissions[9] = '\0';
    for (size_t i = 0; i < 9; i++)
    {
        if (!(mode & 1 << (8 - i))) // mode &100  ; mode & 010 ; mode & 001;
        {
            permissions[i] = '-';
        }
    }

    return permissions;
}
int main(int argc, char *argv[])
{
    key_t key = ftok("tess.c",'a');
    int shmid = shmget(key,4096,IPC_CREAT|0664);
    ERROR_CHECK(-1,shmid,"shmget");
    char * p = shmat(shmid,NULL,0);
    ERROR_CHECK(NULL,p,"shmat");
    struct shmid_ds stat;
    //获取共享内存信息；
    shmctl(shmid,IPC_STAT,&stat);
    printf("%s\n",ctime(&stat.shm_atime));
    printf("%s\n",get_permissions(stat.shm_perm.mode));
    printf("%d\n",stat.shm_perm.cuid);

    puts(p);
    
    //取消映射；
    shmdt(p);
    //释放内存
    shmctl(shmid,IPC_RMID,NULL);
    return 0;
}
